<?php
namespace app\beautiful\logic\order;
use app\beautiful\logic\FreightLogic;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\PinTuanGoodsModel;
use app\beautiful\model\mall\PinTuanGoodsSkuModel;
use app\beautiful\model\mall\PinTuanGroupModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\order\PinTuanOrderItemModel;
use app\beautiful\model\order\PinTuanOrderModel;
use app\beautiful\model\setting\SettingBalanceModel;
use app\beautiful\model\setting\SettingIntegralModel;

class OrderPinTuanLogic{
    use OrderTrait;
    protected $pin_tuan_goods_data=[];
    protected $total_price=0;
    protected $member_coupon_id;
    protected $pin_tuan_sku_datas=[];
    protected $pin_tuan_order_item_data=[];
    protected $num;
    protected $pin_tuan_group;
    protected $pin_tuan_goods;

    public function createOrder($params)
    {

        //判断用户
        empty($params['member_id']) && $this->error('请先登录后再操作');
        $this->checkMember($params['member_id'], false);

        //判断拼团团队
        $pin_tuan_group_id=$this->checkPinTuanGroup($params['pin_tuan_group_id']);

        //判断商品
        if(empty($params['goods']) || !is_array($params))  $this->error('请选择商品');
        if(count($params['goods'])>1) $this->error('拼团只能选择一个商品');
        $this->checkGoods($params['goods'][0],false);


        //判断配送方式
        if( empty($params['logistics_type']) || !in_array($params['logistics_type'],[1,2])) $this->error('请选择配送方式');
        //快速配送判断邮寄地址
        if($params['logistics_type']==1){
            empty($params['receiving_name']) && $this->error('请输入收货人');
            if(empty($params['receiving_mobile']) || ( !is_mobile($params['receiving_mobile']) && !is_phone($params['receiving_mobile'])))  $this->error('请输入收货人手机号');
            empty($params['receiving_address_province']) && $this->error('请输入收货省份');
            empty($params['receiving_address_city']) && $this->error('请输入收货城市');
            empty($params['receiving_address_county']) && $this->error('请输入收货城镇');
            empty($params['receiving_address_info']) && $this->error('请输入收货具体地址');
        }

        //判断总价
        if(empty($params['total_price'])) $this->error('参数错误#1');
        if((float)$params['total_price'] != $this->total_price) $this->error('参数错误#2');

        //判断优惠卷
        $coupon_id = $params['coupon_id'] ?? 0;
        $couponBalance=0;
        if(!empty($coupon_id)){
            if(null === $myCoupon =  MemberCouponModel::find($coupon_id)) $this->error('优惠券不存在');
            if($myCoupon->status == 1 || $myCoupon->money_limit > $this->total_price) $this->error('该优惠券不可用');
            if($myCoupon->member_id != $params['member_id'])  $this->error('该优惠券不可用');
            $couponBalance = $myCoupon->coupon_money;
        }

        //判断积分抵扣
        $use_integral=(int)$params['use_integral'];
        if($use_integral==1){
            $integral_balance=$this->getIntegralBalance($this->total_price);
        }
        $integral=isset($integral_balance) ? $integral_balance['integral'] : 0;
        $balance=isset($integral_balance) ? $integral_balance['balance'] : 0;


        //获取邮费
        $freight = 0;
        if($params['logistics_type']==1){
            $province= empty($params['receiving_address_province']) ? '' : $params['receiving_address_province'];
            $freight_logic= new FreightLogic($this->shopId);
            $freight=$freight_logic->getFreightPrice($province,$this->num);
            if($freight==-1) $this->error('收货地址暂不支持发货');
        }

        //获取需要支付的金额
        $need_pay=round((($this->total_price)*100 + $freight*100 - $couponBalance*100 - $balance*100)/100,2);

        //保存订单
        $pin_tuan_order_model = new PinTuanOrderModel();
        $pin_tuan_order_data=[
            'shop_id'=>$this->shopId,
            'logistics_type'=>$params['logistics_type'],
            'member_id'=>$params['member_id'],
            'member_face'=>$this->member->face,
            'member_name'=>$this->member->nick_name,
            'total_price'=>$this->total_price,
            'need_pay'=>$need_pay,
            'freight'=>$freight,
            'member_coupon_id'=>$params['coupon_id'],
            'coupon_money'=>$couponBalance,
            'use_integral'=>isset($integral_balance) ? $integral_balance['integral'] : 0,
            'integral_balance'=>isset($integral_balance) ? $integral_balance['balance'] : 0,
            'pin_tuan_group_id'=>$pin_tuan_group_id,
            'group_size'=>$this->pin_tuan_order_item_data['group_size'],
            'is_paid'=>0,
            'status'=>1,
        ];
        if($params['logistics_type']==1){
            $pin_tuan_order_data['receiving_name']=$params['receiving_name'];
            $pin_tuan_order_data['receiving_mobile']=$params['receiving_mobile'];
            $pin_tuan_order_data['receiving_address_province']=$params['receiving_address_province'];
            $pin_tuan_order_data['receiving_address_city']=$params['receiving_address_city'];
            $pin_tuan_order_data['receiving_address_county']=$params['receiving_address_county'];
            $pin_tuan_order_data['receiving_address_info']=$params['receiving_address_info'];
        }
        $pin_tuan_order_model->save($pin_tuan_order_data);

        //保存订单商品
        $this->pin_tuan_order_item_data['pin_tuan_order_id']=$pin_tuan_order_model->pin_tuan_order_id;
        $pin_tuan_order_item_model= new PinTuanOrderItemModel();
        $pin_tuan_order_item_model->save($this->pin_tuan_order_item_data);

        //保存秒杀商品
        $pin_tuan_goods_model=new PinTuanGoodsModel();
        $pin_tuan_goods_model->saveAll($this->pin_tuan_goods_data);

        //保存商品规格
        $pin_tuan_goods_sku_model = new PinTuanGoodsSkuModel();
        $pin_tuan_goods_sku_model->saveAll($this->pin_tuan_sku_datas);

        return $pin_tuan_order_model->pin_tuan_order_id;
    }

    public function getIntegralBalance($total_price)
    {
        $SettingBalance = SettingBalanceModel::where([['shop_id','=', $this->shopId]])->find();
        if(null === $SettingBalance){
            $integral_deduction_balance_limit_rate = 0;
        }else{
            $integral_deduction_balance_limit_rate = $SettingBalance->integral_deduction_balance_limit_rate; //积分抵扣的比率 百分比
        }
        $integralSetting = SettingIntegralModel::where([['shop_id','=', $this->shopId]])->find();
        if($integralSetting === null){ //如果是空 代表不使用积分抵扣余额
            $integral_exchange_balance = 0;
        }else{
            $integral_exchange_balance = $integralSetting->integral_exchange_balance;//汇率
        }

        $pre_can_exchange_balance=round(($total_price*($integral_deduction_balance_limit_rate*100))/10000,2);
        $pre_can_exchange_integral=$integral_exchange_balance==0 ? 0 : round(($pre_can_exchange_balance*10000)/($integral_exchange_balance*100),0);
        $member_integral=$this->member->integral;
        if($member_integral>=$pre_can_exchange_integral){
            $return=[
                'integral'=>$pre_can_exchange_integral,
                'balance'=>$pre_can_exchange_balance
            ];
        }else{
            $return=[
                'integral'=>$member_integral,
                'balance'=>round(($member_integral*($integral_exchange_balance*100))/10000,2),
            ];
        }
        return $return;

    }

    public function checkPinTuanGroup($pin_tuan_group_id)
    {
        if(empty($pin_tuan_group_id) || $pin_tuan_group_id==0) return 0;
        $pin_tuan_group=PinTuanGroupModel::find($pin_tuan_group_id);
        if(null === $pin_tuan_group) $this->error('拼团团队不存在');
        if($pin_tuan_group->shop_id != $this->shopId) $this->error('拼团团队不存在');
        if($pin_tuan_group->group_size<=$pin_tuan_group->num) $this->error('拼团已完成');
        if($pin_tuan_group->status != 1) $this->error('拼团已完成或者已取消');
        if(($pin_tuan_group->add_time+86400)<time()) $this->error('此拼团已超过期限');
        if(null !== PinTuanOrderModel::where([
                ['shop_id','=',$this->shopId],
                ['member_id','=',$this->member->member_id],
                ['pin_tuan_group_id','=',$pin_tuan_group_id],
                ['status','in',[1,2]],
            ])->find()){
            $this->error('您已经在团中了');
        }
        $this->pin_tuan_group=$pin_tuan_group;
        return $pin_tuan_group_id;
    }

    public function checkGoods($datas,$lock)
    {
        empty($datas['pin_tuan_goods_id']) && $this->error('参数错误#3');
        empty($datas['num']) && $this->error('参数错误#4');

        $this->num = ($this->num ?? 0) + $datas['num'];

        $pin_tuan_goods=PinTuanGoodsModel::where([
            ['shop_id','=',$this->shopId],
            ['status','=',1],
            ['is_delete','=',0],
            ['pin_tuan_goods_id','=',$datas['pin_tuan_goods_id']],
            ['quota','>',$datas['num']],
        ])->field('pin_tuan_goods_id,goods_id,pin_tuan_price,quota,take_count,fictitious_take_count,is_have_sku,group_num,start_time,end_time')
            ->lock($lock)->find();
        if(null ===$pin_tuan_goods)  $this->error('请选择商品');
        $group_size=$pin_tuan_goods->group_num;

        if($this->pin_tuan_group){
            if($datas['pin_tuan_goods_id'] != $this->pin_tuan_group->pin_tuan_goods_id) $this->error('拼团商品与团队不匹配');
            $group_size=$this->pin_tuan_group->group_size;
        }else{
            $today=date("Y-m-d",time());
            if($pin_tuan_goods->start_time > $today || $pin_tuan_goods->end_time < $today) $this->error('该商品不在拼团中');
        }

        $goods=GoodsModel::find($pin_tuan_goods->goods_id);
        empty($goods) && $this->error('商品不存在');

       $pin_tuan_goods_sku_id=isset($datas['pin_tuan_goods_sku_id']) ? $datas['pin_tuan_goods_sku_id'] : 0;
       if($pin_tuan_goods_sku_id != 0){
           $pin_tuan_sku=PinTuanGoodsSkuModel::where([
               ['shop_id','=',$this->shopId],
               ['is_delete','=',0],
               ['pin_tuan_goods_id','=',$datas['pin_tuan_goods_id']],
               ['pin_tuan_goods_sku_id','=',$pin_tuan_goods_sku_id],
               ['quota','>',$datas['num']]
           ])->field('pin_tuan_goods_sku_id,name,original_price,pin_tuan_price,quota,take_count')
               ->lock($lock)->find();
           if(null === $pin_tuan_sku) $this->error($goods->name.'的规格缺货');
        }

        //处理订单商品表
        $this->pin_tuan_order_item_data=[
            'shop_id'=>$this->shopId,
            'goods_id'=>$datas['pin_tuan_goods_id'],
            'goods_name'=>$goods->name,
            'goods_cover_img'=>$goods->cover_img,
            'goods_sku_id'=>$pin_tuan_goods_sku_id,
            'goods_sku_name'=>isset($pin_tuan_sku) ? $pin_tuan_sku->name : '',
            'goods_original_price'=>isset($pin_tuan_sku) ? $pin_tuan_sku->original_price : $goods->original_price,
            'group_size'=> $group_size,
            'goods_price'=>isset($pin_tuan_sku) ? $pin_tuan_sku->pin_tuan_price : $pin_tuan_goods->pin_tuan_price,
            'goods_num'=>$datas['num'],
        ];

        $price=isset($pin_tuan_sku) ? $pin_tuan_sku->pin_tuan_price :  $pin_tuan_goods->pin_tuan_price;
        $this->total_price=round((($this->total_price)*100+$price*$datas['num']*100)/100,2);

       //处理秒杀商品表
        $pin_tuan_goods=$pin_tuan_goods->toArray();
        $pin_tuan_goods['quota']=$pin_tuan_goods['quota']-$datas['num'];
        $pin_tuan_goods['take_count']=$pin_tuan_goods['take_count']+$datas['num'];
        $pin_tuan_goods['fictitious_take_count']=$pin_tuan_goods['fictitious_take_count']+$datas['num'];
        $this->pin_tuan_goods_data[]=$pin_tuan_goods;

       //处理规格表
        if(isset($pin_tuan_sku)){
            $pin_tuan_sku=$pin_tuan_sku->toArray();
            $pin_tuan_sku['quota']=$pin_tuan_sku['quota']-$datas['num'];
            $pin_tuan_sku['take_count']=$pin_tuan_sku['take_count']+$datas['num'];
            $this->pin_tuan_sku_datas[]=$pin_tuan_sku;
        }

    }
}